package com.bdy.lm.browser.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.bdy.lm.common.model.User;

/**
 * DAO实现类
 * @author Selfmade
 *
 */
//@Transactional(readOnly=false)
@Repository("userDao")
public class UserDao {
	
	@Autowired
	private SessionFactory sessionFactory;

	@Transactional(readOnly = true)
    public void addUser(User user) {
    	sessionFactory.getCurrentSession().save(user);
//    	sessionFactory.getCurrentSession().flush();
    	Session session = sessionFactory.getCurrentSession();
//    	session.setFlushMode(FlushMode.AUTO);
//    	session.beginTransaction();
//    	session.setDefaultReadOnly(true);
//    	session.save(user);
//    	System.out.println("getFlushMode:" + session.getFlushMode());
    	System.out.println("isReadOnly:" + session.isReadOnly(user));
    	System.out.println("isDefaultReadOnly:" + session.isDefaultReadOnly());
//    	System.out.println("isAlive:" + session.getTransaction().isActive());
    	
//    	session.flush();
//    	user.setIdentity("dd");
//    	session.flush();
//    	session.save(user);
//    	session.getTransaction().commit();
    	
//    	Session session = sessionFactory.openSession();
//    	session.beginTransaction();
//    	session.save(user);
//    	session.getTransaction().commit();
    	System.out.println("id:" + user.getId());
		//return true;
	}
    
	@SuppressWarnings("unchecked")
	public User queryUser(User user) {
		String hql = "from User u where u.name = '" + user.getName() + "' and u.password = '" + user.getPassword() + "'";
		List<User> users = sessionFactory.getCurrentSession().createQuery(hql).list();
		if (users!= null && users.size() > 0) {
			return users.get(0);
		}
		return null;
	}
	
	public void updateUser(User user) {
		sessionFactory.getCurrentSession().update(user);
	}

	public void deleteUser(User user) {
		sessionFactory.getCurrentSession().delete(user);
	}
}

